package com.tl.sun.ui.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.blankj.utilcode.utils.LogUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.tl.sun.AppContext;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.event.AddEtEnvent;
import com.tl.sun.event.CollectEvent;
import com.tl.sun.helper.UIHelper;
import com.tl.sun.model.GroupEntity;
import com.tl.sun.model.base.BaseEntity;
import com.tl.sun.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：HQY on 17/8/9 17:02
 * 邮箱：hqy_xz@126.com
 */

public class AddEtDialogFragment extends DialogFragment {


    @Bind(R.id.tv_title_add)
    TextView mTvTitleAdd;
    @Bind(R.id.tv_title_submit)
    TextView mTvTitleSubmit;
    @Bind(R.id.et_title_name)
    EditText mEtTitleName;
    private String type;
    private String lineId;

    public static AddEtDialogFragment newInstance(String type, String lineId) {

        Bundle args = new Bundle();
        args.putString(UIHelper.ADD_ET, type);
        args.putString(UIHelper.LINE_ID, lineId);
        AddEtDialogFragment fragment = new AddEtDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (EmptyUtils.isNotEmpty(getArguments())) {
            type = getArguments().getString(UIHelper.ADD_ET);
            lineId = getArguments().getString(UIHelper.LINE_ID);
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.Dialog_Tips);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_add_et, null);
        builder.setView(view);
        builder.setCancelable(false);
        ButterKnife.bind(this, view);
        initView();
        return builder.create();
    }

    private void initView() {
        if (type.equals("1")) {
            mTvTitleAdd.setText("收藏到分组");
        } else {
            mTvTitleAdd.setText("修改备注");
        }
        LogUtils.e("打开了");
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.tv_title_submit)
    public void onViewClicked() {
        String etContent = mEtTitleName.getText().toString();
        if (type.equals("1")) {
            addCollect(etContent);
        } else {
            updateRemark(etContent);
        }
    }

    /**
     * 添加分组
     *
     * @param name
     */
    private void addCollect(String name) {
        Map<String, String> map = new HashMap<>();
        map.put("name", name);
        map.put("type", "add");
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/update_group")
                .tag("et")
                .params(map)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseEntity base = AppContext.getBaseEntity(s);
                        if (base.getRet() == 0) {
                            Gson gson = new Gson();
                            Type groupType = new TypeToken<BaseEntity<GroupEntity>>() {
                            }.getType();
                            BaseEntity<GroupEntity> mCollect = gson.fromJson(s, groupType);
                            EventBus.getDefault().post(new CollectEvent(mCollect.getData().getId(), "1"));
                            dismiss();
                        } else if (base.getRet() == -1) {
                            ToastUtil.showToast(base.getMsg());
                        }
                    }
                });
    }

    /**
     * 添加备注
     *
     * @param name
     */
    private void updateRemark(final String name) {
        Map<String, String> map = new HashMap<>();
        map.put("line_id", lineId);
        map.put("remark", name);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/remark_update")
                .tag("ip")
                .params(map)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseEntity base = AppContext.getBaseEntity(s);
                        if (base.getRet() == 0) {
                            EventBus.getDefault().post(new AddEtEnvent("2", name));
                            dismiss();
                        } else {
                            ToastUtil.showToast(base.getMsg());
                        }
                    }
                });
    }
}
